﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Brettle.Web.NeatUpload;
using System.Collections.Generic;
using System.IO;
using EQT.Model;
using EQT.Dal;

public partial class _UploadFiles : System.Web.UI.Page
{
    private DaTfile datfile = new DaTfile(DaCommon.DefaultDb);
    private DaContract dacontract = new DaContract(DaCommon.DefaultDb);
    private DaSampleParameter dasp = new DaSampleParameter(DaCommon.DefaultDb);
    private DaSampleKept daSample = new DaSampleKept(DaCommon.DefaultDb);
    private DaNotice daNotice = new DaNotice(DaCommon.DefaultDb);
    private DaTestCatalog daCatalog = new DaTestCatalog(DaCommon.DefaultDb);
    private DaTestItem daItem = new DaTestItem(DaCommon.DefaultDb);
    private DaFileTemplate daTemplate = new DaFileTemplate(DaCommon.DefaultDb);
    private DaEquip daEquip = new DaEquip(DaCommon.DefaultDb);

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            string m = Request.QueryString["m"];
            if (!String.IsNullOrEmpty(m) && m.Trim().Equals("1")) //多文件
            {
                panelUploadMulti.Visible = true;
                UpdatePanel1.Visible = false;
            }
            else //单个
            {
                UpdatePanel1.Visible = true;
                panelUploadMulti.Visible = false;
            }
            //TODO:查询字符串应该加密
            if (Request.QueryString[null] == "docs")//当是为了文档管理而上传
            {
                ViewState["UPLOAD_MODE"] = "docs";
                #region 为了文档管理而上传所需要的各种参数信息
                string dirid = Request.QueryString["dirid"];
                if (String.IsNullOrEmpty(dirid) || dirid.Trim().Length == 0)
                {
                    Utility.SiteError("缺失所必需的参数【目录编号】", Response);
                }
                else
                {
                    ViewState["DIRID"] = dirid.Trim();
                }
                string dirname = Request.QueryString["dirname"];
                if (String.IsNullOrEmpty(dirname) || dirname.Trim().Length == 0)
                {
                    Utility.SiteError("缺失所必需的参数【目录名称】", Response);
                }
                else
                {
                    ViewState["DIRNAME"] = dirname.Trim();
                }


                labelUploadContext.Text = String.Format("在目录【{0}】，编号【{1}】下添加文件：", dirname, dirid);

                #endregion
            }
            else if (Request.QueryString[null] == "parameterfile")    //为了合同而上传参数文件
            {
                ViewState["UPLOAD_MODE"] = "parameterfile";
                string report_id = Request.QueryString["report_id"];//获取合同ID号
                if (String.IsNullOrEmpty(report_id) || report_id.Trim().Length == 0)
                {
                    Utility.SiteError("缺失所必需的参数【合同编号】", Response);
                }
                else
                {
                    ViewState["REPORT_ID"] = report_id;
                }
                MoContract mo = dacontract.GetEntity(report_id);
                labelUploadContext.Text = String.Format("为客户【{0}】合同【{1}】上传参数文件：",
                    mo.Corp_Name, report_id);

            }
            else if (Request.QueryString[null] == "notice") //为通知上传附件
            {
                //给定通知的EID，给定通知标题，给定返回URL

                ViewState["UPLOAD_MODE"] = "notice";
                string notice_id = Request.QueryString["id"];//获取合同ID号
                if (String.IsNullOrEmpty(notice_id) || notice_id.Trim().Length == 0)
                {
                    Utility.SiteError("缺失所必需的参数【通知编号】", Response);
                }
                else
                {
                    ViewState["NOTICE_ID"] = notice_id;
                }
                MoNotice mo = daNotice.GetEntity(notice_id);
                labelUploadContext.Text = String.Format("为通知【{0}】【{1}】上传附件：",
                    mo.Notice_Id, mo.Notice_Content.Substring(0, (mo.Notice_Content.Length > 10) ? 10 : mo.Notice_Content.Length) + "...");
            }
            else if (Request.QueryString[null] == "sample") //为样品上传附件
            {
                //给定样品的EID，给定样品标题，给定返回URL

                ViewState["UPLOAD_MODE"] = "sample";
                string sampleid = Request.QueryString["id"];//获取合同ID号
                if (String.IsNullOrEmpty(sampleid) || sampleid.Trim().Length == 0)
                {
                    Utility.SiteError("缺失所必需的参数【样品编号】", Response);
                }
                else
                {
                    ViewState["SAMPLE_ID"] = sampleid;
                }
                MoSampleKept mo = daSample.GetEntity(sampleid);
                labelUploadContext.Text = String.Format("为样品【{0}】【{1}】上传附件：",
                    mo.Sam_Kep_Id, mo.Sample_Name.Substring(0, (mo.Sample_Name.Length > 10) ? 10 : mo.Sample_Name.Length) + "...");
            }
            else if (Request.QueryString[null] == "testitem") //为检验项上传附件
            {
                //给检验项的EID，给定返回URL

                ViewState["UPLOAD_MODE"] = "testitem";
                string templateid = Request.QueryString["id"];//获取检验项ID号
                string type = Request.QueryString["type"];

                string rtnctgid = Request.QueryString["rtn_ctgid"];
                string rtnitemid = Request.QueryString["rtn_itemid"];
                string pageindex = Request.QueryString["pageindex"];

                if (String.IsNullOrEmpty(templateid) || templateid.Trim().Length == 0 || String.IsNullOrEmpty(type) || type.Trim().Length == 0)
                {
                    Utility.SiteError("缺失所必需的参数【检验项编号或模板类型】", Response);
                }
                else
                {
                    ViewState["TEMPLATE_ID"] = templateid;
                    ViewState["TEMPLATE_TYPE"] = type;

                    ViewState["RTN_CTG_ID"] = rtnctgid;
                    ViewState["RTN_ITEM_ID"] = rtnitemid;
                    ViewState["PAGEINDEX"] = pageindex;
                }

                MoFileTemplate mot = daTemplate.GetEntity(templateid);
                MoTestCatalog moc = daCatalog.GetEntity(mot.Item_Code);

                labelUploadContext.Text = String.Format("为检验项【{0}】【{1}】上传{2}模板：",
                    moc.TestCtgId, moc.TestCtgName.Substring(0, (moc.TestCtgName.Length > 10) ? 10 : moc.TestCtgName.Length) + "...", type == "doc" ? "Word" : "Excel");
            }
            else if (Request.QueryString[null] == "nameplate") //为设备照片铭牌上传附件
            {
                //给设备ID，给定返回URL

                ViewState["UPLOAD_MODE"] = "nameplate";
                string deviceid = Request.QueryString["deviceid"];//获取设备ID号

                if (String.IsNullOrEmpty(deviceid) || deviceid.Trim().Length == 0)
                {
                    Utility.SiteError("缺失所必需的参数【设备编号或模板类型】", Response);
                }
                else
                {
                    ViewState["DEVICEID"] = deviceid;
                }

                MoEquip moe = daEquip.GetEntity(deviceid);

                labelUploadContext.Text = String.Format("为设备【{0}】上传铭牌图片：", moe.Equip_Id + ":" + moe.Equip_Name);
            }
            else
            {
                Utility.SiteError("未知的文档上传请求", Response);
            }
        }
    }

    protected void btnUpload1_Click(object sender, EventArgs e)
    {
        if (this.IsValid && inputFileId1.HasFile)
        {
            inputFileId1.MoveTo(Path.Combine(Request.PhysicalApplicationPath + "temp\\", inputFileId1.FileName),
                MoveToOptions.Overwrite);
        }

        if (this.IsValid && inputFileId1.HasFile)
        {
            string file_id = SequenceKeys.GenerateFileID();
            //写到本地时的全路径，用URL表达
            string localpath = System.IO.Path.Combine(SiteConfig.File_Repository_Location,
                file_id + System.IO.Path.GetExtension(inputFileId1.FileName));
            inputFileId1.MoveTo(localpath, MoveToOptions.Overwrite);

            MoTfile motfile = new MoTfile();
            motfile.File_Id = file_id;
            motfile.File_Length = inputFileId1.FileContent.Length;
            motfile.File_Name = inputFileId1.FileName; //原始文件的名称，含扩展名，不含路径    
            motfile.File_Url = Utility.GetUri4LocalFile(localpath);

            string upload_mode = ViewState["UPLOAD_MODE"].ToString();
            switch (upload_mode)
            {
                case "docs":
                    {
                        #region 为文档管理而上传
                        MoDirFile modf = new MoDirFile();
                        modf.Df_Id = file_id;
                        modf.Df_Name = inputFileId1.FileName;
                        modf.Df_Flag = "F";
                        modf.Parent_Did = ViewState["DIRID"].ToString();
                        try
                        {
                            datfile.AddFileEx(modf, motfile);
                        }
                        catch (DalException de)
                        {
                            Utility.GlobalLog.Error("添加单个文件失败!", de);
                            Utility.SiteError("添加单个文件失败!" + de.Message, Response);
                        }
                        #endregion
                        break;
                    }
                case "parameterfile":
                    {
                        #region 参数文件上传
                        MoSampleParameter mosp = new MoSampleParameter();
                        mosp.SampleId = SequenceKeys.GenerateSampleID();
                        mosp.ReportId = ViewState["REPORT_ID"].ToString();
                        mosp.RegDate = DateTime.Today;
                        mosp.RefParFile = file_id;

                        try
                        {
                            dasp.AddSampleParameterFile(motfile, mosp);
                        }
                        catch (DalException de)
                        {
                            Utility.GlobalLog.Error("为合同添加参数文件上传失败!", de);
                            Utility.SiteError("为合同添加参数文件上传失败!" + de.Message, Response);
                        }
                        break;
                        #endregion
                    }
                case "notice"://公告附件
                    {
                        MoRefFile modref = new MoRefFile();
                        modref.Eid = ViewState["NOTICE_ID"].ToString();
                        modref.File_Id = motfile.File_Id;
                        modref.Rf_Id = SequenceKeys.GenerateReferFileID();
                        try
                        {
                            datfile.AddFileEx(motfile, modref);
                        }
                        catch (DalException de)
                        {
                            Utility.GlobalLog.Error("添加单个文件失败!", de);
                            Utility.SiteError("添加单个文件失败!", Response);
                        }
                        break;
                    }
                case "sample"://样品附件
                    {
                        MoRefFile modref = new MoRefFile();
                        modref.Eid = ViewState["SAMPLE_ID"].ToString();
                        modref.File_Id = motfile.File_Id;
                        modref.Rf_Id = SequenceKeys.GenerateReferFileID();
                        try
                        {
                            datfile.AddFileEx(motfile, modref);
                        }
                        catch (DalException de)
                        {
                            Utility.GlobalLog.Error("添加单个文件失败!", de);
                            Utility.SiteError("添加单个文件失败!", Response);
                        }
                        break;

                    }
                case "testitem"://检验项
                    {
                        MoRefFile modref = new MoRefFile();
                        modref.Eid = ViewState["TEMPLATE_ID"].ToString();
                        modref.File_Id = motfile.File_Id;
                        modref.Rf_Id = SequenceKeys.GenerateReferFileID();
                        try
                        {
                            if (ViewState["TEMPLATE_TYPE"].ToString() == "doc")
                            {
                                daItem.AddTemplateDoc(motfile, modref);
                            }
                            else
                            {
                                daItem.AddTemplateXls(motfile, modref);
                            }
                        }
                        catch (DalException de)
                        {
                            Utility.GlobalLog.Error("添加单个文件失败!", de);
                            Utility.SiteError("添加单个文件失败!", Response);
                        }
                        break;

                    }
                case "nameplate":
                    {
                        MoRefFile modref = new MoRefFile();
                        modref.Eid = ViewState["DEVICEID"].ToString();
                        modref.File_Id = motfile.File_Id;
                        modref.Rf_Id = SequenceKeys.GenerateReferFileID();
                        try
                        {
                            datfile.AddFileEx(motfile, modref);
                        }
                        catch (DalException de)
                        {
                            Utility.GlobalLog.Error("添加单个文件失败!", de);
                            Utility.SiteError("添加单个文件失败!", Response);
                        }
                        break;
                    }
                default: break;
            }
            inputFileId1.Dispose();
        }
    }

    protected void btnUploadMulti_Click(object sender, EventArgs e)
    {
        if (multiFileId2.Files.Length > 0)
        {
            List<MoTfile> fileList = new List<MoTfile>(multiFileId2.Files.Length);
            List<MoDirFile> dfList = new List<MoDirFile>(multiFileId2.Files.Length);

            uploadPre.InnerText += "批次上传 " + multiFileId2.Files.Length + " 文件:\n";
            foreach (UploadedFile file in multiFileId2.Files)
            {
                string file_id = SequenceKeys.GenerateFileID();
                //写到本地时的全路径，用URL表达
                string localpath = System.IO.Path.Combine(SiteConfig.File_Repository_Location,
                    file_id + System.IO.Path.GetExtension(file.FileName));
                try
                {
                    file.MoveTo(localpath, MoveToOptions.Overwrite);
                }
                catch (SystemException se)
                {
                    Utility.GlobalLog.Error("上传文件失败！", se);
                    uploadPre.InnerText += Environment.NewLine + String.Format("上传文件【{0}】失败！", file.FileName) + Environment.NewLine + se.Message;
                    break;
                }

                MoDirFile modf = new MoDirFile();
                modf.Df_Id = file_id;
                modf.Df_Name = file.FileName;
                modf.Df_Flag = "F";
                modf.Parent_Did = ViewState["DIRID"].ToString();

                MoTfile motfile = new MoTfile();
                motfile.File_Id = file_id;
                motfile.File_Length = file.ContentLength;
                motfile.File_Name = file.FileName; //原始文件的名称，含扩展名，不含路径    
                motfile.File_Url = Utility.GetUri4LocalFile(localpath);

                fileList.Add(motfile);
                dfList.Add(modf);
                uploadPre.InnerText += file.FileName + "\n";
            }
            try
            {
                datfile.AddFileEx(dfList, fileList);
            }
            catch (DalException de)
            {
                Utility.GlobalLog.Error("批量添加文件失败!", de);
                Utility.SiteError("批量添加文件失败!" + de.Message, Response);
            }



        }
    }
    //单击了返回按钮
    protected void btnReturn_Click(object sender, EventArgs e)
    {
        string upload_mode = ViewState["UPLOAD_MODE"].ToString();
        string return_url = String.Empty;
        switch (upload_mode)
        {
            case "docs"://返回至文档查看页面
                {
                    return_url = String.Format("docs.aspx?dir_id={0}", ViewState["DIRID"]);
                    break;
                }
            case "parameterfile"://返回至合同查看页面
                {
                    return_url = String.Format("CreateContract.aspx?reportid={0}", ViewState["REPORT_ID"]);
                    break;
                }
            case "notice"://公告
                {
                    return_url = String.Format("notice.aspx?edit&noticeid={0}", ViewState["NOTICE_ID"]);
                    break;
                }
            case "sample": //样品
                {
                    return_url = String.Format("SampleKept.aspx?edit&sampleid={0}", ViewState["SAMPLE_ID"]);
                    break;
                }
            case "testitem": //检验项
                {
                    return_url = String.Format("TestItem.aspx?rtnctgid={0}&rtnitemid={1}&pageindex={2}", ViewState["RTN_CTG_ID"], ViewState["RTN_ITEM_ID"], ViewState["PAGEINDEX"]);
                    break;
                }
            case "nameplate":
                {
                    return_url = String.Format("Equipment.aspx?deviceid={0}&mode={1}", ViewState["DEVICEID"], "edit");
                    break;
                }
            default:
                {
                    return_url = "/";
                    break;
                }
        }
        Response.Redirect(return_url);

    }
}
